ALTER TABLE Promotion
ADD CheckinCode VARCHAR(4) NOT NULL DEFAULT('')
GO
CREATE TABLE [dbo].[PromotionCheckin](
	[PromotionCheckinId] [int] IDENTITY(1,1) NOT NULL,
	[PromotionId] [int] NOT NULL,
	[UserId] [int] NOT NULL,
	[DateCheckin] [datetime] NOT NULL,
 CONSTRAINT [PK_PromotionCheckin] PRIMARY KEY CLUSTERED 
(
	[PromotionCheckinId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[PromotionCheckin]  WITH CHECK ADD  CONSTRAINT [FK_PromotionCheckin_Promotion] FOREIGN KEY([PromotionId])
REFERENCES [dbo].[Promotion] ([PromotionId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PromotionCheckin] CHECK CONSTRAINT [FK_PromotionCheckin_Promotion]
GO
ALTER TABLE [dbo].[PromotionCheckin]  WITH CHECK ADD  CONSTRAINT [FK_PromotionCheckin_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[PromotionCheckin] CHECK CONSTRAINT [FK_PromotionCheckin_User]
GO
ALTER TABLE [dbo].[PromotionCheckin] ADD  CONSTRAINT [DF_PromotionCheckin_DateCheckin]  DEFAULT (getdate()) FOR [DateCheckin]
GO
CREATE PROCEDURE spAPI_Promotion_Checkin
(
	@Token VARCHAR(255),
	@PromotionId INT,
	@Code VARCHAR(4)
)
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @IdResult INT
	DECLARE @UserId INT
	DECLARE @Result XML
	
	SET @IdResult = 0
	EXEC spAPI_User_CheckToken @Token = @Token, @Result = @IdResult OUT, @UserId = @UserId OUT
	
	IF @IdResult = 1
		IF EXISTS(SELECT 1 FROM Promotion WHERE PromotionId = @PromotionId AND CheckinCode = @Code AND StatusCode = 'ACT')
		BEGIN
			IF NOT EXISTS(SELECT 1 FROM PromotionCheckin WHERE PromotionId = @PromotionId AND UserId = @UserId)
				INSERT INTO PromotionCheckin
				(PromotionId, UserId)
				VALUES (@PromotionId, @UserId)
		END			
		ELSE
			SET @IdResult = -1

	SELECT @IdResult AS IdResult, ISNULL(@Result, '') AS Result		
END
GO


